package cn.information.view.baseinfo.baseinfo;

import cn.information.bean.Product;
import cn.information.dao.ProductDao;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class ProductAddUI extends JFrame {
    private JComboBox<String> ComboBoxAdd;
    private JButton btnConfirm;

    public ProductAddUI() {
        setTitle("商品类型查询");
        setSize(400, 200);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        JPanel panelCenter = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 20));
        JPanel panelSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        // 获取所有商品类型
        ProductDao productDao = new ProductDao();
        List<Product> products = productDao.findAll();
        String[] name = products.stream()
                .map(Product::getSpname)
                .distinct()
                .toArray(String[]::new);

        panelCenter.add(new JLabel("请选择要添加的商品:"));
        ComboBoxAdd = new JComboBox<>(name);
        panelCenter.add(ComboBoxAdd);

        btnConfirm = new JButton("确认");
        btnConfirm.setEnabled(false); // Initially disabled
        panelSouth.add(btnConfirm);

        JButton btnCancel = new JButton("取消");
        btnCancel.addActionListener(e -> dispose());
        panelSouth.add(btnCancel);

        add(panelCenter, BorderLayout.CENTER);
        add(panelSouth, BorderLayout.SOUTH);

        // Add listener to combo box
        ComboBoxAdd.addActionListener(e -> {
            if (ComboBoxAdd.getSelectedIndex() >= 0) {
                btnConfirm.setEnabled(true);
            } else {
                btnConfirm.setEnabled(false);
            }
        });

        // Add listener to confirm button
        btnConfirm.addActionListener(e -> {
            String selectedAdd = (String) ComboBoxAdd.getSelectedItem();
            new ProductAddputUI(selectedAdd).setVisible(true);
            dispose();
        });

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            new ProductAdd().setVisible(true);
//        });
//    }
}
